package engine.newUi
{
	import engine.GameData;
	import engine.data.ModelLocator;
	import engine.data.Record;
	import engine.event.SoundEvent;
	import engine.flag.ResourcesPath;
	import engine.logic.login.WaitingForScene;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.scene.SceneChangeManager;
	import engine.tip.TipsMainLogic;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.Timer;
	
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	import newx.utils.MemoryOptimise;
	
	/**
	 * 副本战斗结算Logic 
	 * @author liuel
	 * 
	 */	
	public class ActionEctypeResultLogic
	{
		private var   _model            :ModelLocator;
		private static  var _self      :ActionEctypeResultLogic;
		private var   _ui                :ActionEctypeResultUI;
		/**掉落物品数组**/
		private var _itemArr             :Array = [];
		/**队伍信息数组**/
		private var _teamArr             :Array = [];
		/**队伍人数**/
		private var teamCount           :int =0;
		/**物品格子对大数目**/
		private var _itemgroupMax        :uint ;
		/**队伍格子对大数目**/
		private var _teamgroupMax        :uint ;
		/**掉落物品数量**/
		private var _itemCount           :int=0;
		/**保存经验值控件**/
		private var _txtArr              :Array;
		private var _time                :Timer;
		private var _itemMC              :MovieClip;
		private var _img                 :NxClip;

		/**离开函数**/
		private var _leftFun            :Function = null;
		/**再来一次函数**/
		private var _againFunc          :Function =null;
		private var _isHave			 :Boolean;
		private var _txtCount   		: NxLabel;
		private var _gold				:int;
		
		private var _luckVal			:int;
		/**副本类型**/
		private var _typeFB			:int =1;
		private var _first				:Boolean;
		private var _bossBoxNew		:MovieClip;
		//山神庙第一层副本闯过次数
		private var times:int =0;
		public static function getInstance():ActionEctypeResultLogic
		{
			if(_self == null)
			{
				_self = new ActionEctypeResultLogic();
				
			}
			return _self;
		}
		public function ActionEctypeResultLogic()
		{
		}
		public function Init():void
		{   
			initInfo();
		}
		private function initInfo():void
		{
			_time         = new Timer(40,20);
			_ui           = ActionEctypeResultUI.getInstance();
			_model       = ModelLocator.getInstance();
			MemoryOptimise.stopMovie(_ui.bossBox);
			_itemgroupMax = _ui.bootyGroup.col*_ui.bootyGroup.row;
			_teamgroupMax = _ui.teamGroup.row*_ui.teamGroup.col;
			initGroup(_ui.teamGroup,_teamgroupMax);
			initGroup(_ui.bootyGroup,_itemgroupMax);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SEND_ACTIONECTYPE_INFO),onAcceptTeam);
		}
		public function BeforeShow():void
		{
			
//			_ui.bootyGroup.visible = false;
			_ui.bossBox.visible=false;
//			_ui.btn1.visible       = false;
//			_ui.btn2.visible       = false;
			
//			if( null != _bossBoxNew && _ui.bossBox != _bossBoxNew )
//			{
//				_ui.bossBox.parent.addChild( _bossBoxNew );
//				_bossBoxNew.x = _ui.bossBox.x;
//				_bossBoxNew.y = _ui.bossBox.y;
//				_ui.bossBox = _bossBoxNew;
//			}
			_ui.bossBox.visible    = false;
			_ui.bossBox.gotoAndStop(1);
			addEvent();
			
			var lv:int = int(StaticIni.getIniVar("ActionEctypeResult_Guide","showLvevl"));
			if(_model.scene.Role.getPlayerLevel()<=lv)
			{
				_ui.guideMc.visible = true;
				_ui.guideMc.play();
			}
			else
			{
				_ui.guideMc.visible = false;
				_ui.guideMc.stop();
			}
			_ui.guideMc.mouseChildren = _ui.guideMc.mouseEnabled = false;
//			if( !_first )
//			{
//				ResManager.loadRes( "custSkin_0002", "res/swf/custSkin_0002.swf", onComplete );
//				_first = true;
//				
//				function onComplete( swf : DisplayObject, pList : * ):void
//				{
//					_bossBoxNew = ( swf as MovieClip ) .getChildAt( 0 ) as MovieClip;
//				}
//			}
		}
		public function AfterHide():void
		{
			removeEvent();
		}
		private function addEvent():void
		{
			_time.addEventListener(TimerEvent.TIMER,addExperience);
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			_ui.btn1.addEventListener(MouseEvent.CLICK,onClickBtn1);
			_ui.btn2.addEventListener(MouseEvent.CLICK,onClickBtn2);
			_ui.bootyGroup.addItemsEvent(MouseEvent.MOUSE_OVER,onShowTips);
			_ui.bootyGroup.addItemsEvent(MouseEvent.MOUSE_OUT,onHideTips);
		}
		private function removeEvent():void
		{
			_ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			_ui.btn1.removeEventListener(MouseEvent.CLICK,onClickBtn1);
			_ui.btn2.removeEventListener(MouseEvent.CLICK,onClickBtn2);
//			_ui.bossBox.removeEventListener(MouseEvent.CLICK,onClickbossBox);
			_ui.bootyGroup.removeItemsEvent(MouseEvent.MOUSE_OVER,onShowTips);
			_ui.bootyGroup.removeItemsEvent(MouseEvent.MOUSE_OUT,onHideTips);
			
//			_ui.bossBox.removeEventListener(MouseEvent.ROLL_OVER,onShowGolw);
//			_ui.bossBox.removeEventListener(MouseEvent.ROLL_OUT, onHideGolw);
			
		}
		private function onShowGolw(e:MouseEvent):void
		{
			_ui.bossBox.gotoAndStop(6);
		}
		private function onHideGolw(e:MouseEvent):void
		{
			_ui.bossBox.gotoAndStop(7);
		}
		private function initGroup(group :NxViewGroup,num:int):void
		{
			
			var txt1		:TextField;
			var txt2        :TextField;
			var PlyType		:NxClip
			for(var i : int = 0 ; i < num ; i ++)
			{
				_itemMC =	group.getItemByIndex(i);
				_txtCount   =	new NxLabel();
				_img				=	new NxClip();
				_img.defaultImage=	null;
				_img.isCache		=	true;

				_itemMC["infoTxt4"].text="";
				if(group == _ui.teamGroup)
				{
					_img.width	=	 _img.height	=	50;
					_img.x =_itemMC["img2"].x+1;
					_img.y =_itemMC["img2"].y+2;
					//队伍
					txt1=_itemMC["titleTxt2"];   //第一行玩家名字
					txt1.text=""
					txt1.autoSize = TextFieldAutoSize.LEFT;
					txt1.height = 17;
					_itemMC.mouseChildren = false;
					txt2=_itemMC["infoTxt5"];
					txt2.text=""
//					txt2.autoSize = TextFieldAutoSize.LEFT;
					_itemMC["infoTxt5"].width =100;
				}
				else
				{
					//战利品
					_img.x	=	_itemMC["img2"].x-1;
					_img.y	=	_itemMC["img2"].y;
					
					txt1			=_itemMC["titleTxt2"]	
					txt1.text=""
					txt1.wordWrap =false;
					txt1.autoSize = TextFieldAutoSize.LEFT;
					txt1.height = 17;
					
					_txtCount.x= _itemMC["img2"].x-1;
					_txtCount.y= _itemMC["img2"].y;
					_itemMC.mouseChildren = false;
					_itemMC["txtCount"] = _txtCount;
					(_itemMC["infoTxt4"] as TextField).autoSize  =TextFieldAutoSize.LEFT;
					
				}
                _itemMC["img"]  = _img ;
				_itemMC.addChild(_img);
				_itemMC.addChild(_txtCount);
				_img.scaleContent	=	true;
				_img.maintainAspectRatio	=	false;
				
				
			}
		}
		/**
		 * 更新一个玩家信息 
		 * @param index 人物所在数组索引
		 * @param item
		 * 
		 */		
		private function updataTeamGroup(index : int, arr : Array):void
		{
			
			var itemMC	 	: MovieClip	=	_ui.teamGroup.getItemByIndex(index);
			if(itemMC != null)
			{	
				if(index >= teamCount || arr[index*3] == undefined )
				{
					itemMC.visible = false;
					return;
				}
				itemMC.visible     = true;
				var clothModel:int=0;
				if(index ==0)
				{
					clothModel=_model.scene.Role.clotheModel
				}
		
				(itemMC["img"] as NxClip).source            = ResourcesPath.getMiniHeadPic(arr[index*3+1],clothModel); //"res/photos/head_"  + arr[index*3+1] + ".png";
				if(index == 0 )
				{
					itemMC["titleTxt2"].htmlText   =  arr[index*3]+"";
				}
				else
				{
					var name:String = StaticIni.getSwfLangStr(arr[index*3]);
					itemMC["titleTxt2"].htmlText  =  name;
				}
				itemMC["infoTxt4"].text=StaticIni.getSwfLangStr("UIStr_1001157");
				itemMC["infoTxt5"] .text= "0";
				_txtArr.push(itemMC["infoTxt5"])
			}
		}
		/**
		 * 
		 * 
		 * 更新队伍信息 
		 * @param index 人物所在数组索引
		 * @param item
		 * 
		 */		
		private function updataGroup(arr:Array):void
		{
			_txtArr=[];
			for(var i : int = 0; i < _teamgroupMax; i ++)
			{
				updataTeamGroup(i, arr);
			}
			_model.dispatchEvent(new SoundEvent(SoundEvent.ROUND_NUM));
		}
		/**
		 * 清除一个玩家信息 
		 * @param index
		 * 
		 */		
		private function removeTeamGroup(index : int):void
		{
			var itemMC : MovieClip = _ui.teamGroup.getItemByIndex(index);
			
			if(itemMC != null)
			{
				(itemMC["img"] as NxClip).source = "";
				(itemMC["img"] as NxClip).clear();
				itemMC["titleTxt2"].text ="";
				itemMC["infoTxt5"] .htmlText="";
				itemMC["infoTxt4"].text="";
			}
		}
		/**
		 * 清除队伍信息
		 * @param group
		 * 
		 */		
		private function clearTeamGroup():void
		{
			for(var i : int = 0; i < teamCount; i ++)
			{
				removeTeamGroup(i);
			}
		}
		
		/**
		 * 更新一个物品信息 
		 * @param index
		 * @param arr
		 * 
		 */		
		private function updataItemGroup(index : int, arr : Array):void
		{
			
			 _itemMC	=	_ui.bootyGroup.getItemByIndex(index);
			if(_itemMC != null)
			{	
				if(index>=_itemCount||arr[index*2] == undefined)
				{
					_itemMC.visible = false;
					return;
				}
				 _itemMC.visible    = true;
				
				if(index ==0)
				{
					_itemMC["titleTxt2"].htmlText = StaticIni.getSwfLangStr("CapitalType_0");
					if(_isHave)
					{
						_itemMC["infoTxt4"].htmlText =StaticIni.getSwfLangStrVar("UIString_1000152",[_luckVal]);
					}
					else
					{
						_itemMC["infoTxt4"].htmlText ="";
					}
					(_itemMC["img"] as NxClip).source            =  ResourcesPath.getPropsURL(arr[index]);
				}
				else
				{
					var obj:Object=StaticIni.getIniObj(_itemArr[index*2]);
					(_itemMC["img"] as NxClip).source            =  ResourcesPath.getPropsURL(int(obj["Photo"]));  //"res/items/icon_"  + obj["Photo"] + ".jpg";
					var name:String=StaticIni.getSwfLangStr(obj["NameID"]);
					_itemMC["titleTxt2"].htmlText   =name;
					
				}
				_itemMC["txtCount"].text =_itemArr[index*2+1];
				_itemMC["date"] =_itemArr[index*2];
			}
		}
		/**
		 * 更新物品信息 
		 * @param index 物品所在数组索引
		 * @param item
		 * 
		 */		
		private function updataItem(arr:Array):void
		{
			if(_itemCount>_ui.bootyGroup.col)
			{
				_ui.bootyGroup.y=_ui.floor3.y+20;
			}
			else
			{
				_ui.bootyGroup.y=_ui.floor3.y+40;
			}
			for(var i : int = 0; i < _itemgroupMax; i ++)
			{
				updataItemGroup(i, arr);
			}
			
		}
		
		/**
		 * 清除一个物品信息 
		 * @param index
		 * 
		 */		
		private function removeItemGroup(index : int):void
		{
			var itemMC : MovieClip = _ui.bootyGroup.getItemByIndex(index);

			if(itemMC != null)
			{
				(itemMC["img"] as NxClip).source = "";
				(itemMC["img"] as NxClip).clear();
				itemMC["titleTxt2"].text ="";
				itemMC["infoTxt4"].text ="";
				_itemMC["date"] =null;
			}
		}
		/**
		 * 清除所有掉落物品信息
		 * @param group
		 * 
		 */		
		private function clearItemGroup():void
		{
			for(var i : int = 0; i < teamCount; i ++)
			{
				removeItemGroup(i);
			}
		}
		/**
		 * 播放动画 
		 * @param movie  需要播放的对象	
		 * @param index  停止的位置
		 * 
		 */		
		private function animation(movie:MovieClip,index:int):void
		{
			movie.gotoAndPlay(1);
			movie.addFrameScript(index,function():void
			{
				movie.stop();
				movie.addFrameScript(index,null);
//				//如果当前播放的是宝箱
//				if(movie == _ui.bossBox)
//				{
//					if(_typeFB == 1)
//					{
//						_ui.btn1.visible=times ==1?false:true;
//					}
//					else
//					{
//						_ui.btn1.visible = false;
//					}
//					_ui.btn2.visible       = true;
//					_ui.bootyGroup.visible = true;	
//					_ui.bossBox.visible    = false;
//				}
			} );
			
		}
		
		
		/**
		 * 根据分计算等级 
		 * @param val 分
		 * @return 
		 * 
		 */		
		private function computeActionLevel(val:int):int
		{
			var vl:int=Math.ceil(val/20);
			return vl;
		}
		/**
		 * 
		 * @param arr 用于显示的等级数组[胜利等级,星级]
		 * 
		 */
		private function setStarCondition(val:int):void
		{
			var imMC:MovieClip;
	        for(var i:int=0;i<5;i++)
			{
				 imMC=_ui.star.getItemByIndex(i);
				
				if(i<val)
				{
					imMC.gotoAndStop(2);
				}
				else
				{
					imMC.gotoAndStop(1);
				}
//				imMC.gotoAndStop(2);
			}
			var strID:String="";
			switch(val)
			{
				case 1:
					strID="FBScore_1";
					break;
				case 2:
					strID="FBScore_2";
					break;
				case 3:
					strID="FBScore_3";
					break;
				case 4:
					strID="FBScore_4";
					break;
				case 5:
					strID="FBScore_5";
					break;
			}
			_ui.text2.htmlText =StaticIni.getSwfLangStr(strID);
		}
		
		/**
		 * 动态经验值增加 
		 * 
		 */		
		private function addExperience(e:TimerEvent):void
		{
			for each (var txt:TextField in _txtArr) 
			{
				var sI:int=int(txt.text);
				var index:int=_txtArr.indexOf(txt);
				var targetEx:int=_teamArr[index*3+2];
				var sp:Number=targetEx/_time.repeatCount;
				if(sp<1)
				{
					sp =1;
				}
				if(_time.currentCount==_time.repeatCount)
				{
					txt.text="+"+targetEx+"";
//					_ui.bossBox.visible=true;
//					animation(_ui.bossBox,_ui.bossBox.totalFrames-1);
//					_model.dispatchEvent(new SoundEvent(SoundEvent.OPEN_BOX));
					
				}
				else
				{
					if(int(sI+sp)==targetEx)
					{
						txt.text="+"+targetEx;
						
//						_ui.bossBox.visible=true;
//						animation(_ui.bossBox,_ui.bossBox.totalFrames-1);
//						_model.dispatchEvent(new SoundEvent(SoundEvent.OPEN_BOX));
						_time.reset();
					}
					txt.text="+"+int(sI+sp)+"";
				}
			}
			if(_time.currentCount == _time.repeatCount)
			{
				_time.removeEventListener(TimerEvent.TIMER,addExperience);
				_time.reset();
			}
		}
		private function CloseTimer(e:TimerEvent):void
		{   
			if(_time !=null)
			{
				_time.reset();
			}
		}
		
		////////////////////////////////////////////回调函数///////////////////////////////////////////////////
		/**
		 
		 * 播放SWF完成回调函数
		 */		
		private function onSceneBGLoadComplete():void
		{
			
			WaitingForScene.end();
			
		}
		///////////////////////////////////////////监听函数/////////////////////////////////////////////////////
		private function onClickClose(e:NxWindowEvent):void
		{
			_ui.hide();
		}
		/**
		 * 点击宝箱 
		 * @param e
		 * 
		 */	    
		private function onClickbossBox(e:MouseEvent):void
		{
			_ui.bossBox.removeEventListener(MouseEvent.ROLL_OVER,onShowGolw);
			_ui.bossBox.removeEventListener(MouseEvent.ROLL_OUT, onHideGolw);
			animation(_ui.bossBox,_ui.bossBox.totalFrames-1);
			_model.dispatchEvent(new SoundEvent(SoundEvent.OPEN_BOX));
		}
		/**
		 * 点击再次挑战 
		 * @param e
		 * 
		 */		
		private function onClickBtn1(e:MouseEvent):void
		{
			_againFunc();
			_ui.hide();
		}
		/**
		 * 点击离开 
		 * @param e
		 * 
		 */		
		private function onClickBtn2(e:MouseEvent):void
		{
			_leftFun();
		}
		private function onShowTips(e:MouseEvent):void
		{
			var str:String="";
			var mc:MovieClip =e.currentTarget as MovieClip;
			if(mc == null)
			{
				return;
			}
			else if(mc.date ==48001069) //铜钱
			{
				str=StaticIni.getSwfLangStr("CapitalTips_0");
				TipsMainLogic.instance.showString(str);
				return
			}
			else if(mc.date ==33990001)  //修为
			{
				str=StaticIni.getSwfLangStr("CapitalTips_3");
				TipsMainLogic.instance.showString(str);
				return
			}
			else if(mc.date ==33990002)	 //元宝
			{
				str=StaticIni.getSwfLangStr("CapitalTips_4");
				TipsMainLogic.instance.showString(str);
				return;
			}
			var obj:Object =TipsMainLogic.instance.getStaticObjWithID(mc.date);
			if(obj == null)
				return;
			TipsMainLogic.instance.showMain(obj);
		}
		private function onHideTips(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
		/**
		 *获取第一个副本测通关次数 
		 * @param arr
		 * @return 
		 * 
		 */		
		private function getTimes(arr:Array):int
		{
			for(var i:String in arr)
			{
				if(arr[int(i)][0] ==11000201)
				{
					return arr[int(i)][1];
				}
			}
			return -1;
		}
		private function updateBtn():void
		{
			var record:Record =_model.scene.GetRecordEx("FBCompleteRec");
			times =getTimes(record.recArr);
			if(_typeFB == 1)
			{
				_ui.btn1.visible=true;
				if(int(	GameData.SceneConfig) == 11000201)
				{
					_ui.btn1.visible=times ==1?false:true;
				}
				
			}
			else
			{
				_ui.btn1.visible = false;
			}
			
			if(_ui.btn1.visible)
			{
				_ui.btn2.x =327;
				_ui.guideMc.x = 209;
			}
			else
			{
				_ui.btn2.x =206;
				_ui.guideMc.x =81;
			}
			
		}
		/**
		 * 接受队伍信息
		 * @param e  
		 * 
		 */	
		private function onAcceptTeam(e:CustomMsgEvent):void
		{
			
			_teamArr=[];
			var  infoArr:Array =[];
			infoArr = e.pList;
			_typeFB = infoArr.shift();//副本类型  1普通副本 2精英副本
			updateBtn();
			var   val:int             = infoArr.shift();  //攻击分
			var  level:int           = computeActionLevel(val);
			animation(_ui.attack,level);
			animation(_ui.defense,level);
			_ui.text4.htmlText=StaticIni.getSwfLangStrVar("UIString_1000162",[val]);//"总分："+val+"";
			setStarCondition(level);
			teamCount              = infoArr.shift();
			for(var i:int=0;i<teamCount*3 ;i++)
			{
				_teamArr.push(infoArr.shift())
			}

			if(_ui.created ==false)
			{
				_ui.show();
				addPanle();
			}
			clearTeamGroup();
			updataGroup(_teamArr);
			starAnimation();
			_gold = infoArr.shift();
			_luckVal= infoArr[0];
			if(_luckVal!=0)
			{
				_isHave=true
			}
			else
			{
				_isHave =false;
			}
			_itemCount= (infoArr.length-1)/2;
			var _itemArr  :Array    = [];	
			_itemArr.push(48001069);
			_itemArr.push(_gold);
			for(var j:int =1;j<=_itemCount*2;j++)
			{
				_itemArr.push(infoArr[j]);
			}
			onDropItem(_itemArr);
		}
		/**
		 *添加蒙板 
		 * 
		 */		
		public function addPanle():void
		{
			var p:Point=new Point(0,0);
			_ui.graphics.clear();
			_ui.graphics.beginFill(0xfff111,0.0);
			p=_ui.globalToLocal(p);
			_ui.graphics.drawRect(p.x,p.y,SceneChangeManager.getGameWidth(),SceneChangeManager.getGameHeight());
			_ui.graphics.endFill();
			
		}
		/**
		 *经验动画开始 
		 * 
		 */		
		private function starAnimation():void
		{
			_time.start();
		}
		/**
		 * 接受掉落物品信息
		 * @param arr 掉落物品数组
		 * 
		 */		
		private function  onDropItem(arr:Array):void
		{
			_itemArr=[];
			_itemCount=arr.length/2;
	
			
			_itemArr=arr;
			
		
			updataItem(_itemArr);
		}
		
		public function setFunc( leaveFunc : Function, againFightFunc : Function ):void
		{
			_leftFun    = leaveFunc;
			_againFunc  = againFightFunc;
		}
	}
}